const echarts = require('../../utils/echarts-mini')

Component({
  properties: {
    ec: { type: Object, value: {} },
    forceUseOldCanvas: { type: Boolean, value: false },
    canvasId: { type: String, value: 'ec-canvas' }
  },
  data: { isUseNewCanvas: false },
  observers: {
    'ec': function(newEc) {
      if (newEc && newEc.onInit) { this.initChart() }
    }
  },
  lifetimes: {
    attached() { this.initCanvas() },
    detached() { if (this.chart) { this.chart.dispose(); this.chart = null } }
  },
  methods: {
    initCanvas() {
      const useNewCanvas = !this.properties.forceUseOldCanvas && wx.canIUse('canvas.type')
      this.setData({ isUseNewCanvas: useNewCanvas })
      setTimeout(() => { this.initChart() }, 50)
    },
    initChart() {
      if (!this.properties.ec || !this.properties.ec.onInit) return
      if (this.data.isUseNewCanvas) { this.initNewCanvas() } else { this.initOldCanvas() }
    },
    initNewCanvas() {
      const query = this.createSelectorQuery()
      query.select('.ec-canvas').fields({ node: true, size: true }).exec((res) => {
        if (!res || !res[0]) return
        const canvas = res[0].node
        const ctx = canvas.getContext('2d')
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = res[0].width * dpr
        canvas.height = res[0].height * dpr
        ctx.scale(dpr, dpr)
        this.chart = this.properties.ec.onInit(canvas, res[0].width, res[0].height, dpr)
      })
    },
    initOldCanvas() {
      const ctx = wx.createCanvasContext(this.properties.canvasId, this)
      const query = this.createSelectorQuery()
      query.select('.ec-canvas').boundingClientRect((res) => {
        if (!res) return
        const dpr = wx.getSystemInfoSync().pixelRatio
        const canvas = { width: res.width * dpr, height: res.height * dpr, getContext: () => ctx, addEventListener: () => {}, removeEventListener: () => {}, dispatchEvent: () => {} }
        this.chart = this.properties.ec.onInit(canvas, res.width, res.height, dpr)
      }).exec()
    },
    touchStart(e) { if (this.chart && this.chart.getZr) { this.chart.getZr().handler.dispatch('mousedown', { zrX: e.touches[0].x, zrY: e.touches[0].y }) } },
    touchMove(e) { if (this.chart && this.chart.getZr) { this.chart.getZr().handler.dispatch('mousemove', { zrX: e.touches[0].x, zrY: e.touches[0].y }) } },
    touchEnd() { if (this.chart && this.chart.getZr) { this.chart.getZr().handler.dispatch('mouseup', {}) } }
  }
})

